/**
 * @MovieClipBmp.as
 * 
 * @author sodaChen mail:asframe@qq.com
 * @version 1.0
 * <br>Copyright (C), 2010-2016 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:ASFrame
 * <br>Date:2016-5-16
 */
package com.asframe.display.movie
{
	import com.asframe.display.bmp.BitmapMovie;
	import com.asframe.display.data.FrameData;
	import com.asframe.utils.DisplayUtils;
	import com.asframe.utils.RefUtils;
	
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.geom.Rectangle;
	
	/**
	 * MovieClip进行Bitmap序列化
	 * @author sodaChen
	 * Date:2016-5-16
	 */
	public class MovieClipBmp extends BitmapMovie
	{
		public static var BITMAP_TPYE:int = 1;
		public static var MOVIE_TPYE:int = 2;
		
		/** 原作为资源的MC **/
		private var _type:int;
		private var _resMovie:MovieClip;
		private var _nextFrame:int;
		private var _swfName:String;
		
		public function MovieClipBmp(pixelSnapping:String="auto", smoothing:Boolean=false)
		{
			super(pixelSnapping, smoothing);
		}
		public function setResMovie(_resMovie:MovieClip,_type:int = 1):void
		{
			this._resMovie = _resMovie;
			this._type = _type;
			//保存最大帧数
			mStart = 0;
			if(_type == MOVIE_TPYE)
			{
				mEnd = mTotalFrame = _resMovie.totalFrames;
			}
			else
			{
				mEnd = mTotalFrame = _resMovie.posList.length;
				_swfName = _resMovie.swfName + "_";
			}
			mEnd = mTotalFrame;
			mCurrentFrame = _nextFrame = 0;
			mFrames = new Vector.<FrameData>(mEnd);
			mBitmapDatas = new Vector.<BitmapData>(mEnd);
			//必须转换第一帧
			transMovie();
		}
		public override function gotoAndStop(stopFrame:int=-1):void
		{
			super.gotoAndStop(stopFrame);
			if(bitmapData == null)
			{
				//表明之前没有缓存过的资源，则进行新的转换
				transMovie();
				bitmapData = mBitmapDatas[mCurrentFrame];
			}
		}
		public override function tick():void
		{
			_nextFrame = mCurrentFrame + 1;
			if(_nextFrame < mEnd && mBitmapDatas[_nextFrame] == null)
			{
				transMovie();
			}
			super.tick();
		}
		private function transMovie():void
		{
			var frameData:FrameData = new FrameData();
			var rect:Rectangle;
			var bmpData:BitmapData;
			//根据类型生成新的
			if(_type == MOVIE_TPYE)
			{
				//影片转换成BitmapData,一帧帧转换
				_resMovie.gotoAndStop(mCurrentFrame + 1);
				rect = _resMovie.getBounds(_resMovie);
				bmpData = DisplayUtils.drawBitmapData(_resMovie,rect,true);
			}
			else
			{
				//这里可以写成扩展，接口等处理方式，用于支持和兼容不同的swf数据格式
				//直接反射出来
				bmpData = RefUtils.refImage(_swfName + mCurrentFrame,_resMovie.loaderInfo.applicationDomain);
				//从swf里复制出信息当前帧图像的偏移坐标
				rect = new Rectangle(int(_resMovie.posList[mCurrentFrame].x),int(_resMovie.posList[mCurrentFrame].y),bmpData.width,bmpData.height);
			}
			frameData.initFrames(bmpData,rect);
			mFrames[_nextFrame] = frameData;
			mBitmapDatas[_nextFrame] = bmpData;
		}
	}
}